package service

import (
	"encoding/json"
	"errors"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/models"
	"rock/customer/modules/redisModules"
	"rock/customer/public"
	"time"
)

type User struct {
}

// 用户 - 创建
func (u *User) CreateUser(c *gin.Context, tx *gorm.DB, user *models.WkbUsers) error {
	err := tx.SetCtx(public.GetGinTraceContext(c)).Create(user).Error
	if err != nil {
		return err
	}
	if user.ID > 0 {
		userDetail := models.WkbUserDetail{
			UId:           int(user.ID),
			Mobile:        user.Mobile,
			Nickname:      user.Name,
			LastLoginTime: time.Now(),
			ImUserType:    1,
		}
		err = u.CreateUserDetail(c, tx, userDetail)
		if err != nil {
			return err
		}
		_, err = u.setUserDetail(c, tx, gconv.String(user.ID))
		if err != nil {
			return err
		}
	}
	return err
}

// 用户 - 用户详情
func (u *User) UserByUserId(c *gin.Context, tx *gorm.DB, userId string) (data dto.UserDetail, err error) {
	// 取缓存
	redisCache := redisModules.ClientRedis.Get(initParam.UserPrefix + gconv.String(userId))
	val, err := redisCache.Result()
	if err == nil {
		err = json.Unmarshal([]byte(val), &data)
		if err != nil {
			return
		}
		return
	} else {
		if err != redis.Nil {
			return
		}
	}
	// 查db
	err = tx.SetCtx(public.GetGinTraceContext(c)).Model(&models.WkbUserDetail{}).
		Where("uid = ?", userId).Scan(&data).Error
	if err != nil {
		if err.Error() != gorm.ErrRecordNotFound.Error() {
			err = errors.New(initParam.DataIsNotExist)
			return
		}
	}
	if data.UserId == 0 {
		err = errors.New(initParam.DataIsNotExist)
		return
	}
	// 存缓存
	err = addRedis(data, initParam.UserPrefix + gconv.String(userId), 3*24*time.Hour)
	return
}

// 用户 - 用户详情
func (u *User) UserByUnionId(c *gin.Context, tx *gorm.DB, unionId string) (data dto.UserDetail, err error) {
	common := &Common{}
	userId := common.UnionIdToUserId(c, tx, unionId)
	if userId == "" {
		creatUser := &models.WkbUsers{
			UnionID:       unionId,
			OverdueDate:   time.Now().Add(48 * time.Hour),
			ExpireDate:    time.Now().Add(48 * time.Hour),
			LastLoginTime: time.Now(),
			ImUserType:    1,
		}
		err = u.CreateUser(c, tx, creatUser)
		//创建成功
		if err != nil {
			return
		}
		userId = gconv.String(creatUser.ID)
	}
	data, err = u.UserByUserId(c, tx, userId)
	return
}

// 用户 - 用户详情 - 创建
func (u *User) CreateUserDetail(c *gin.Context, tx *gorm.DB, userDetail models.WkbUserDetail) error {
	return tx.SetCtx(public.GetGinTraceContext(c)).Create(&userDetail).Error
}

// 用户 - 用户详情 - 更新
func (u *User) UpdateUser(c *gin.Context, tx *gorm.DB, userId string, param map[string]interface{}) error {
	userDetail := &models.WkbUserDetail{}
	return tx.SetCtx(public.GetGinTraceContext(c)).Model(userDetail).
		Where("uid = ?", userId).Updates(param).Error
}

// 用户 - 用户详情 - 更新缓存
func (u *User) setUserDetail(c *gin.Context, tx *gorm.DB, userId string) (data dto.UserDetail, err error) {
	// 查db
	err = tx.SetCtx(public.GetGinTraceContext(c)).Model(&models.WkbUserDetail{}).
		Where("uid = ?", userId).Scan(&data).Error
	if err != nil {
		if err.Error() != gorm.ErrRecordNotFound.Error() {
			err = errors.New(initParam.DataIsNotExist)
			return
		}
	}
	if data.UserId == 0 {
		err = errors.New(initParam.DataIsNotExist)
		return
	}
	// 存缓存
	err = addRedis(data, initParam.UserPrefix + gconv.String(userId), 3*24*time.Hour)
	return
}
